package com.linkme2night.controller;

import android.util.Log;

import com.linkme2night.model.Venue;
import com.linkme2night.model.VenueDAO;

public class SearchController {

	private Venue venues_data[];
	private VenueDAO venue_dao;

	public SearchController() {
		venue_dao = new VenueDAO();
		venues_data = new Venue[venue_dao.getVenuesIDs().length];

		readData();
	}

	public Venue[] getVenues() {
		return venues_data;
	}

	public Venue[] getVenuesSortedByRank() {
		boolean swapped = true;
		int j = 0;
		Venue tmp;
		while (swapped) {
			swapped = false;
			j++;
			for (int i = 0; i < venues_data.length - j; i++) {
				if (venues_data[i].getRanking() < venues_data[i + 1]
						.getRanking()) {
					tmp = venues_data[i];
					venues_data[i] = venues_data[i + 1];
					venues_data[i + 1] = tmp;
					swapped = true;
				}
			}
		}

		return venues_data;
	}

	public Venue[] getVenuesSortedByName() {
		boolean swapped = true;
		int j = 0;
		Venue tmp;
		while (swapped) {
			swapped = false;
			j++;
			for (int i = 0; i < venues_data.length - j; i++) {
				if (venues_data[i].getName().compareTo(venues_data[i + 1]
						.getName())>0) {
					tmp = venues_data[i];
					venues_data[i] = venues_data[i + 1];
					venues_data[i + 1] = tmp;
					swapped = true;
				}
			}
		}
		
		return venues_data;
	}

	private boolean readData() {
		try {
			for (int i = 0; i < venue_dao.getVenuesIDs().length; i++) {
				int j = venue_dao.getVenuesIDs()[i];
				venues_data[i] = new Venue(venue_dao.getName(j),
						venue_dao.getOverallRanking(j),
						venue_dao.getAddress(j), venue_dao.getLatitude(j),
						venue_dao.getLongitude(j), venue_dao.getDescription(j),
						j);
			}
		} catch (Exception e) {
			Log.d("Linkme2night", "Exception: " + e.getStackTrace());
			return false;
		}

		return true;
	}

}
